﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Web;
using Kickstarter.Models;

namespace WebTV_Kickstarter
{
    [MetadataType(typeof(Rating_Validator))]
    public partial class Rating
    {
        private static EFDataModelContainer db = new EFDataModelContainer();
        // "<option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='8'>8</option><option value='9'>9</option><option value='10'>10</option>"

        public static void AddRating(Rating rating)
        {
            db.RatingSet.Add(rating);
            Project.AddScore(rating.ProjectId,rating.Score,db);
            db.SaveChanges();            
        }

        internal static Rating GetRatingByUser(int userId, int? id)
        {
            return db.RatingSet.Where(r => r.UserId == userId && r.ProjectId == id).FirstOrDefault();
        }

        internal static void EditRating(Rating rating, Rating oldrating)
        {
            int scoreVerschil = rating.Score - oldrating.Score;
            Project.EditScore(oldrating.ProjectId, scoreVerschil,db);
            oldrating.Score = rating.Score;
            db.SaveChanges();
        }

        public static void GiveRating(Rating rating)
        {
            Rating oldrating = null;
            if ((oldrating = GetRatingByUser(rating.UserId, rating.ProjectId)) == null)
                AddRating(rating);
            else
                EditRating(rating, oldrating);
        }
    }
}